Harden RAG retrieval and answer reliability - #1289
Conversation
|
Warning Review limit reached
Next review available in: 2 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (76)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Updates to Preview Branch (codex/rag-reliability-final) ↗︎
Tasks are run on every commit but only new migration files are pushed.
View logs for this Workflow Run ↗︎. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…-final # Conflicts: # docs/outstanding-issues.md
|
@cursoragent run bugbot review |
|
Bugbot review of PR #1289 — APPROVE (exact head FindingsNo high-confidence P0–P2 defects.
Application Residual riskUnapplied BMJ attestation migration ( Checks
Ledger updated and pushed: #1289 |
|
@claude Review this PR |
|
Hi @BigSimmo — thanks for the @claude mention. Open this in Claude Code on the web to continue here: https://claude.ai/code Context: Automated backlink from the Claude backlink workflow. Claude Code can pick up the mention and push a scoped fix to the branch. |
|
Claude encountered an error after 2s —— View job I'll analyze this and get back to you. |
There was a problem hiding this comment.
Pull request overview
This PR hardens high-risk RAG retrieval/answer reliability and source-governance surfaces by tightening evidence binding, improving deterministic/extractive fallbacks, strengthening eval diagnostics + quality gates, and introducing BMJ third‑party attestation support that remains explicitly unverified pending qualified human action.
Changes:
- Strengthens retrieval selection + document lookup chunk selection to preserve intent terms and prevent wrong-subject/table-evidence promotion (notably around clozapine blood-count action shapes and lithium monitoring rows).
- Tightens answer/eval reliability contracts (required expected-file citations, explicit handling of source-backed review stubs, richer retrieval diagnostics persisted into artifacts).
- Adds BMJ third-party attestation policy plumbing across SQL schema/types/tests and admin-only review route behavior that fails closed when the v2 RPC/migration is unavailable.
Reviewed changes
Copilot reviewed 75 out of 76 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| vitest.config.mts | Adds aggregate coverage floors for core RAG/reliability modules. |
| tests/source-review-schema.test.ts | Verifies BMJ attestation migration/schema/types invariants and fail-closed constraints. |
| tests/source-authority-tooling.test.ts | Pins audit/backfill tooling to include source_review_events + BMJ attestation handling. |
| tests/smart-rag-api.test.ts | Ensures extractive comparison planning is described as clinical synthesis with deterministic assembly. |
| tests/retrieval-selection.test.ts | Adds regression cases preventing foreign-medication/foreign-table promotion and preserving subject binding. |
| tests/rag-offline-answer.test.ts | Tightens assertion to require the correct clozapine withhold threshold signal and rejects review-stub routing. |
| tests/rag-fast-path-ordering.test.ts | Guards stable ordering for lithium monitoring rows over higher-scored unrelated tables/foreign rows. |
| tests/rag-eval-cases.test.ts | Adds/strengthens eval case contracts for authoritative citations and review-stub scoring behavior. |
| tests/rag-document-lookup-escalation-rescue.test.ts | Pins the smallest-sufficient rescued evidence instead of incentivizing citation padding. |
| tests/rag-document-lookup-chunk-query.test.ts | Covers the new chunk-query selection behavior (expanded variant only for measured clozapine action shape). |
| tests/rag-answer-text.test.ts | Extends answer-quality heuristics around time-unit phrases (“6 hours”). |
| tests/medication-entities.test.ts | Adds medication entity safety/catalog coverage for foreign-medication detection and binding. |
| tests/eval-utils.test.ts | Adds required-claim + expected-citation binding validation coverage. |
| tests/eval-retrieval.test.ts | Adds assertions for persisted per-row relevance/signal matches in golden retrieval artifacts. |
| tests/eval-quality.test.ts | Adds CLI arg validation, safe dumping constraints, and gating behavior for unsupported-only runs. |
| tests/eval-document-matching.test.ts | Tightens overlap rules with explicit approvals and document-identity dedupe for matching. |
| tests/document-mutation-routes.test.ts | Prevents bulk mutation routes from writing governance status or editing reviewed identity/provenance. |
| tests/clinical-search.test.ts | Adds foreign-threshold label handling and subject-binding regression coverage. |
| tests/clinical-review-queue.test.ts | Extends review queue with authority classification and deterministic top-local evidence manifest. |
| tests/answer-responsiveness-gate.test.ts | Ensures timeout fallback text doesn’t echo user typos. |
| tests/answer-ranking.test.ts | Ensures numeric ranges stay within a single bold span. |
| supabase/schema.sql | Adds source_review_events decision, new columns, and record_source_review_v2 with service-role-only grants. |
| supabase/drift-manifest.json | Updates schema snapshot/hash including new columns/RPC signature. |
| src/lib/supabase/database.types.ts | Exposes new source_review_events columns + record_source_review_v2 args. |
| src/lib/source-review.ts | Implements BMJ attestation policy constants, eligibility checks, and event+metadata completeness verification. |
| src/lib/smart-rag-api.ts | Adjusts intent for multi-document synthesis to reflect extractive-but-synthesis behavior. |
| src/lib/retrieval-selection.ts | Expands FBC matching and centralizes monitoring subject matching via clinical-search helpers. |
| src/lib/rag/rag-source-segmentation.ts | Adds bounded line reflow helpers and atomic NMHS clozapine red-range segment recovery. |
| src/lib/rag/rag-quote-verification.ts | Hardens citation enrichment to only add deterministic support when model-selected citations are directly supported and conflict-free. |
| src/lib/rag/rag-extractive-artifacts.ts | Detects procedural comparator artifacts (ECT flow edge/arrow glyphs) without blanket comparator rejection. |
| src/lib/rag/rag-eval-cases.ts | Adds requiredDirectClaim contract + scoring changes to reject source-backed review stubs as “covered”. |
| src/lib/rag/rag-comparison.ts | Adds safe comparison fallback selection that respects bounded fail-closed families. |
| src/lib/rag/rag-candidate-sources.ts | Narrows expanded chunk-query usage to the measured clozapine blood-count action shape; otherwise preserves raw intent query. |
| src/lib/rag/rag-cache.ts | Bumps cache dependency version to invalidate stale behavior. |
| src/lib/rag/rag-answer-text.ts | Prevents “dose 6 hours” false positives while still flagging missing units. |
| src/lib/eval-document-matching.ts | Adds document-identity-based dedupe + maximum matching to prevent one physical doc satisfying multiple expected slots. |
| src/lib/clinical-value-binding.ts | Adds explicit entity↔value binding helper for clause-scoped safety checks. |
| src/lib/clinical-review-queue.ts | Adds review class, best-rank tracking, and top-local evidence manifest builder. |
| src/app/api/documents/bulk/route.ts | Disallows bulk governance status writes and fails closed on identity/provenance edits for reviewed sources. |
| src/app/api/documents/[id]/reviews/route.ts | Adds BMJ attestation inputs, v2 RPC routing + fail-closed 503 when migration is unapplied, and public-doc cache invalidation. |
| scripts/eval-utils.ts | Implements required-direct-claim semantic contract validation bound to expected-file citations. |
| scripts/eval-retrieval.ts | Persists per-result relevance grade + matched declared signals into golden artifacts for diagnostics. |
| scripts/build-clinical-review-queue.ts | Adds --top-local-manifest + --source-artifact support and emits deterministic manifest/report. |
| scripts/audit-source-governance.ts | Adds service-role-only source_review_events audit to compute operational unattested debt without emitting event evidence. |
| docs/source-governance-refresh-worklist-2026-07-22.md | Updates operator worklist with implemented BMJ policy status + manifest evidence boundaries. |
| docs/rag-hybrid-findings-and-todo.md | Updates backlog items with landed bounded OCR repair + latency profiling evidence. |
| docs/rag-behaviour/refuted-approaches.md | Documents additional refuted approaches and updated irrelevant@10 diagnostics posture. |
| docs/evidence/rag-top-local-review-manifest-2026-07-26.json | Adds auditable top-local evidence manifest (pending qualified human review, no attestation applied). |
| docs/evidence/rag-reliability-evidence-2026-07-27.md | Records local/live evidence paths and outcome metrics for the reliability work. |
| docs/branch-review-ledger.md | Appends a review ledger entry for PR #1289 / codex/rag-reliability-final. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Append an append-only ledger row for tip d49af8a after a Bugbot pass found no P0–P2 on the unchanged application tree. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>
@cursoragent Any issues identified from copilot review? |
|
@CodeRabbit please review |
|
✅ Action performedReview finished.
|
Remove exact duplicate branch-review-ledger rows introduced when merging origin/main so Static PR checks stay green.
Union-merge of concurrent PR #1289 rows produced exact duplicates. Restore docs/branch-review-ledger.md from origin/main and re-append only this PR's disposition rows. Co-authored-by: BigSimmo <BigSimmo@users.noreply.github.com>


Summary
#019admission/discharge source loss and#029review-fallback stubs, with a zero-tolerance quality gate for recurrence.RAG impact: behaviour change — canary pair
output/rag-retrieval-post-final.json->output/rag-retrieval-post-exact-head.json(36/36; document/content recall 1.0; zero per-case document/content RR regressions)The protected retrieval change uses the expanded chunk query only for the measured clozapine blood-count action shape. Discharge and other red-section document lookups retain raw intent terms. Ranking scores, comparator order, clamps, and semantic reranking are unchanged.
Verification
npm run verify:cheap— PASS: 25 gates, including the full unit suite.npm run test:coverage— PASS: 399 files; 4,062 passed, 2 skipped; RAG coverage 86.83% statements and 90.79% lines.npm run eval:rag:offline— PASS: 36 cases, 21 suites, 560 assertions.npm run check:production-readiness— PASS: 8 checks, no blockers; two isolated-worktree environment-location warnings.npm run check:migration-role— PASS.npm run verify:pr-local— PASS on the reconciled application tree: format, zero-warning lint, typecheck, 403 test files / 4,101 passed / 2 skipped, production build/client-secret scan, and 36 offline RAG fixtures.npm run eval:retrieval:quality— PASS on the reconciled application tree: 36/36, document/content recall 1.0, MRR 0.8921, content MRR 0.9406, nDCG 0.9308, irrelevant-at-10 0.0917, zero failures, and zero per-case document/content RR regressions.npm run eval:rag -- --limit 15+npm run eval:quality -- --rag-only— superseded by the recorded full 44-case answer gate above; no weaker sample is claimed.npm run verify:ui— UI verification not run: no UI, routing, styling, or browser-rendering surface changed.npm run verify:release— not run: it includes additional provider-backed release work; exact-head PR-local, the protected retrieval canary, and hosted required checks are the scoped merge gates.npm run check:production-readiness— result recorded above.npm run check:deployment-readiness— not run: deployment startup and hosting configuration were unchanged.Exact-head typechecking passed within
npm run verify:pr-local.Risk and rollout
mainwill follow the repository's normal application/worker auto-deploy path.Migration
20260727010000_bmj_third_party_source_attestation.sqlis a separate, deliberate operator step and must not be applied automatically. Until applied, legacy owner-scoped review behavior remains available and v2-only public/attestation requests fail closed with503 source_review_v2_unavailable.Clinical Governance Preflight
Clinical KB Database(sjrfecxgysukkwxsowpy)Notes
Supersedes draft Harden RAG retrieval and answer reliability #1288 with a clean one-commit history so the deliberately fake token-shaped test fixture is absent from every PR commit.
Current reconciled head:
22b7b751247f1904b11bd53145ac18fbb0330b90.BMJ sources remain
clinical_validation_status=unverified; qualified human review, hosted apply, attestation, and warning-rate remeasurement remain#022.Firefox/WebKit evidence and human irrelevant-at-10 disposition remain
#023.ADHD corpus/table accessibility and metabolic schedule evidence remain the open parts of
#018.